import React, { useEffect, useState } from 'react';
import { Table, Button, TablePaginationConfig, Input, Pagination, Modal, Form, Select, notification, } from 'antd'
import { useForm } from 'antd/es/form/Form'
import { EditOutlined, DeleteOutlined } from "@ant-design/icons"
import type { ColumnsType } from 'antd/es/table'
import { staff_search, role_list, staff_add, staff_del, staff_edit } from "../../../utils/api"
import "../../../styles/Personmanage.scss"

const { Search } = Input;
interface Props {

}

//定义每一行的数据对象类型
interface DataType {
  user: string;
  nickname: string;
  name: string;
  phone: string;
  role: string;
  key: string;
}
function Personmanage(props: Props) {

  //使用from中的userfrom()方法，通过from来绑定要操作的from表单
  const [form] = Form.useForm()

  //表格数据
  var [data, setData] = useState([])
  //保存员工id
  var [id, setId] = useState("")

  //定义变量存页码
  var [newPage, setNewpage] = useState(0)
  var [newPagesize, setNewpagesize] = useState(0)

  //是否弹框
  var [isModalOpen1, setIsModalOpen1] = useState(false)
  var [isModalOpen2, setIsModalOpen2] = useState(false)

  //决定了每一列渲染什么数据
  const columns: ColumnsType<DataType> = [
    {
      title: '账号', //表格列的名字(显示在表格头上)
      dataIndex: 'user', //数据对应的属性名
      //key是必须的,每一列不同.
    },
    {
      title: '昵称',
      dataIndex: 'nickname',

    },
    {
      title: '姓名',
      dataIndex: 'name',


    },
    {
      title: '手机号',
      dataIndex: 'phone',

    },
    {
      title: '类型',
      dataIndex: ['role', 'name']

    },
    {
      title: '角色',
      dataIndex: ['role', 'name']

    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <>
          <i className='iconfont icon-edit' onClick={() => { edit(record) }}><EditOutlined style={{ color: "deepskyblue", cursor: "pointer" }} /></i>
          <span style={{ width: "10px", display: "inline-block" }}></span>
          <i className='iconfont icon-delete' onClick={() => { del(record) }}><DeleteOutlined style={{ color: "red", cursor: "pointer" }} /></i>
        </>
      ),
    },
  ];

  //分页器
  var pagination = {
    current: 1,
    pageSize: 10,
    total: 100
  }

  //搜索
  const onSearch = (value: string) => {

    staff_search({ searchKey: value, page: 1, count: 10 }).then((res) => {
      // console.log(res.data.list);
      var arr = res.data.list.map((item: any) => {
        return {
          user: item.user,
          name: item.name,
          nickname: item.nickname,
          phone: item.phone,
          role: item.role,
          key: item.key
        }
      })
      setData(arr)

    })


  }
  // 引入生命周期方法
  var [options, setOptions] = useState([])
  useEffect(() => {
    //获取角色列表
    role_list().then((res) => {
      var arr = res.data.list.map((item: any) => {
        return { label: item.name, value: item._id }
      })
      setOptions(arr)
    })
    //获取员工列表
    staff_search({ searchKey: '', page: 1, count: 10 }).then((res) => {
      setData(res.data.list);

    })
  }, [])


  //调用分页器的handleclick函数
  const handleClick = (page: any, pageSize: any) => { //接收两个参数
    console.log(pagination);
    //pagination 参数 包含有当前最新页码
    //在这里发请求, 获取最新页码对应的数据
    setNewpage(page)  //获取当前最新页数保存在Newpage中
    setNewpagesize(pageSize) //获取当前最新页数保存在pageSize中
    //发搜索请求（页码）
    staff_search({ searchKey: '', page: page, count: pageSize }).then((res) => {
      setData(res.data.list);
    })
  };
  //挂载时显示人员页面
  useEffect(() => {
    staff_search({ searchKey: '', page: 1, count: 10 }).then((res) => {
      // console.log(res.data.list);
      setData(res.data.list);
    })
  }, [])

  //显示 弹框  新增 + 编辑
  const showModel1 = () => {
    setIsModalOpen1(true);
  };
  const showModel2 = () => {
    setIsModalOpen2(true);
  };

  //隐藏 弹框 新增 + 编辑
  const handleCancel1 = () => {
    setIsModalOpen1(false);
  };
  const handleCancel2 = () => {
    setIsModalOpen2(false);
  };
  //新增
  //表单验证通过 执行
  const onFinish = (values: any) => {
    staff_add(values).then((res) => {
      console.log(res.data.list);
      if (res.data.code == 200) {
        notification.success({ message: "新增成功!", placement: "top" })
        setIsModalOpen1(false);
      } else {
        notification.error({ message: "新增失败!", placement: "top" })
      }
    })
  };

  //删除功能 + 发请求
  var del = (record: any) => {
    console.log(record);
    staff_del({ id: record._id, searchKey: "", page: newPage, count: newPagesize }).then((res) => {
      if (res.data.code == 200) {
        staff_search({ searchKey: '', page: 1, count: 10 }).then((res) => {
          // console.log(res.data.list);
          setData(res.data.list);
          notification.success({ message: "删除成功！", placement: "top" })
        })
      }
      else {
        notification.error({ message: "删除失败！", placement: "top" })
      }
      console.log(res.data.code);

    })
  }

  //点击编辑自动获取vaule值
  var edit = (record: any) => {
    showModel2()
    console.log(record._id);
    setId(record._id)
    form.setFieldsValue(record)
    form.setFieldsValue({
      role: record.role.name
    })

  }

  //编辑发请求
  const onFinish1 = (values: any) => {
    staff_edit({
      _id: id, user: values.user, pass: "kf1234", nickname: values.nickname, name: values.name, phone: values.phone, role: values.role
    }).then((res) => {
      console.log(res.data);
      if (res.data.code == 200) {
        staff_search({ searchKey: '', page: 1, count: 10 }).then((res) => {
          setData(res.data.list);
          notification.success({ message: "编辑成功!", placement: "top" })
          setIsModalOpen2(false);
        })

      } else {
        notification.error({ message: "编辑失败!", placement: "top" })
      }
    })
  };
  return (
    <div className='personmanage'>
      <h4 style={{ marginBottom: "20px" }}>员工管理</h4>
      <div className="opet">
        <Search style={{ width: 300, marginRight: 20 }} placeholder="请输入员工姓名" onSearch={onSearch} enterButton />
        <Button type="primary" onClick={showModel1}>新增员工</Button>
      </div>
      {/* 表格组件 */}
      {/* columns 表格每一列如何渲染 */}
      {/* dataSource 表格的数据源 */}
      <Table columns={columns} dataSource={data} pagination={false} />
      <Pagination defaultCurrent={1} total={500} onChange={handleClick} style={{ marginTop: "20px", marginLeft: "700px" }} />

      {/*   //新增 */}
      <Modal title="新增员工" open={isModalOpen1} onCancel={handleCancel1} >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={onFinish}
        >
          <Form.Item
            label="账号"
            name="user"
            rules={[{
              required: true,
              message: '请输入账号',
            }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="昵称"
            name="nickname"
            rules={[{
              required: true,
              message: '请输入昵称',
            }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="name"
            rules={[{
              required: true,
              message: '请输入姓名',
            }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[{
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入手机号',
            }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="角色"
            name="role"
            rules={[{
              required: true,
              message: '请选择角色',
            }]}
          >
            <Select
              options={options}

            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button type="primary" htmlType="submit">新增员工</Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑 */}

      <Modal title="编辑员工" open={isModalOpen2} onCancel={handleCancel2} >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={onFinish1}
          form={form}
        >
          <Form.Item
            label="账号"
            name="user"
            rules={[{
              required: true,
              message: '请输入账号',
            }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="昵称"
            name="nickname"
            rules={[{
              required: true,
              message: '请输入昵称',
            }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="name"
            rules={[{
              required: true,
              message: '请输入姓名',
            }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="手机号"
            name="phone"
            rules={[{
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入手机号',
            }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="角色"
            name="role"
            rules={[{
              required: true,
              message: '请选择角色',
            }]}
          >
            <Select
              options={options}
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button type="primary" htmlType="submit">编辑员工</Button>
          </Form.Item>
        </Form>
      </Modal>


    </div>

  );
}
export default Personmanage;